﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using SodaCraft.Localizations;
using UnityEngine;

namespace AutoAim.Config
{
    public static class ConfigManager
    {
        private const string ConfigFileName = "AutoAimConfig.json";

        private static string FilePath => Path.Combine(Application.persistentDataPath, "Saves", ConfigFileName);

        private const string ModName = "AutoAim";

        public static void SetupModConfig(AutoAimConfig config)
        {
            if (!ModConfigAPI.IsAvailable())
            {
                Debug.Log("AutoAim ModConfigAPI not available");
                return;
            }

            Debug.Log("准备添加ModConfig配置项");

            // 添加配置变更监听
            ModConfigAPI.SafeAddOnOptionsChangedDelegate(OnModConfigOptionsChanged);

            // 根据当前语言设置描述文字
            SystemLanguage[] chineseLanguages =
            {
                SystemLanguage.Chinese,
                SystemLanguage.ChineseSimplified,
                SystemLanguage.ChineseTraditional
            };

            var isChinese = chineseLanguages.Contains(LocalizationManager.CurrentLanguage);

            // 添加设置项

            // --- 在最上方添加模式选择 ---
            ModConfigAPI.SafeAddDropdownList(
                ModName,
                "aimMode", // 对应 AutoAimConfig.aimMode
                "自瞄模式",
                GetEnumSortedDictionary<AimMode>(isChinese),
                typeof(int),
                config.aimMode);

            // --- 添加吸附模式的专属配置项 ---
            ModConfigAPI.SafeAddInputWithSlider(
                ModName,
                "adsorptionRange", // 对应 AutoAimConfig.adsorptionRange
                "吸附范围",
                typeof(float),
                config.adsorptionRange, new Vector2(10, 500)); // 范围可自定义

            ModConfigAPI.SafeAddInputWithSlider(
                ModName,
                "adsorptionStrength", // 对应 AutoAimConfig.adsorptionStrength
                "吸附强度",
                typeof(float),
                config.adsorptionStrength, new Vector2(0, 1));

            ModConfigAPI.SafeAddDropdownList(
                ModName,
                "adsorptionFalloff", // 对应 AutoAimConfig.adsorptionFalloff
                "吸附衰减模式",
                GetEnumSortedDictionary<AdsorptionFalloff>(isChinese),
                typeof(int),
                config.adsorptionFalloff);

            ModConfigAPI.SafeAddBoolDropdownList(ModName, "writeLog", "写出日志", config.writeLog);

            ModConfigAPI.SafeAddInputWithSlider(
                ModName,
                "gunScatterMultiplier",
                "散布系数",
                typeof(float),
                config.gunScatterMultiplier
                , new Vector2(0, 1));

            ModConfigAPI.SafeAddDropdownList(
                ModName,
                "activationMode",
                "锁敌按键行为",
                GetEnumSortedDictionary<AimActivationMode>(isChinese),
                typeof(int),
                config.activationMode);

            ModConfigAPI.SafeAddDropdownList(
                ModName,
                "targetPart",
                "锁敌部位",
                GetEnumSortedDictionary<AimTargetPart>(isChinese),
                typeof(int),
                config.targetPart);

            ModConfigAPI.SafeAddInputWithSlider(
                ModName,
                "weaponDistanceMultiplier",
                "枪械基础锁敌距离系数",
                typeof(float),
                config.weaponDistanceMultiplier, new Vector2(1, 2));

            ModConfigAPI.SafeAddInputWithSlider(
                ModName,
                "fixedLockDistance",
                "固定锁敌距离",
                typeof(float),
                config.fixedLockDistance, new Vector2(0, 50));

            ModConfigAPI.SafeAddDropdownList(
                ModName,
                "distanceType",
                "锁敌距离类型",
                GetEnumSortedDictionary<AimTargetDistanceType>(isChinese),
                typeof(int),
                config.distanceType);
        }

        private static void OnModConfigOptionsChanged(string key)
        {
            if (!key.StartsWith(ModName + "_"))
                return;

            var config = ModBehaviour.Instance.GetAutoAimConfig();

            // 使用新的 LoadConfig 方法读取配置
            LoadConfigFromModConfig(config);

            // 保存到本地配置文件
            SaveConfig(config);
        }

        public static void LoadConfigFromModConfig(AutoAimConfig config)
        {
            // 使用新的 LoadConfig 方法读取所有配置
            config.distanceType =
                (AimTargetDistanceType)ModConfigAPI.SafeLoad(ModName, "distanceType", (int)config.distanceType);
            config.fixedLockDistance =
                ModConfigAPI.SafeLoad(ModName, "fixedLockDistance", config.fixedLockDistance);
            config.weaponDistanceMultiplier = ModConfigAPI.SafeLoad(ModName, "weaponDistanceMultiplier",
                config.weaponDistanceMultiplier);
            config.targetPart = (AimTargetPart)ModConfigAPI.SafeLoad(ModName, "targetPart", (int)config.targetPart);
            config.gunScatterMultiplier =
                ModConfigAPI.SafeLoad(ModName, "gunScatterMultiplier", config.gunScatterMultiplier);
            config.activationMode =
                (AimActivationMode)ModConfigAPI.SafeLoad(ModName, "activationMode", (int)config.activationMode);

            // config.writeLog = ModConfigAPI.SafeLoad(ModName, "writeLog", config.writeLog);

            config.aimMode = (AimMode)ModConfigAPI.SafeLoad(ModName, "aimMode", (int)config.aimMode);
            config.adsorptionRange = ModConfigAPI.SafeLoad(ModName, "adsorptionRange", config.adsorptionRange);
            config.adsorptionStrength = ModConfigAPI.SafeLoad(ModName, "adsorptionStrength",
                config.adsorptionStrength);
            config.adsorptionFalloff = (AdsorptionFalloff)ModConfigAPI.SafeLoad(ModName, "adsorptionFalloff", (int
                )config.adsorptionFalloff);
        }

        /// <summary>
        /// 生成枚举的SortedDictionary（根据参数决定键值对类型）
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="showDescription">是否使用描述作为键：true（描述-值），false（名称-值）</param>
        /// <returns>包含所有枚举成员的SortedDictionary</returns>
        private static SortedDictionary<string, object> GetEnumSortedDictionary<TEnum>(bool showDescription = false)
            where TEnum : struct, Enum
        {
            // 获取枚举的所有成员（名称+值）
            var enumMembers = Enum.GetValues(typeof(TEnum))
                .Cast<TEnum>()
                .Select(enumValue => new
                {
                    Value = (object)Convert.ToInt32(enumValue), // 枚举值（如 0、1）
                    Name = enumValue.ToString(), // 枚举名称（如 "Fixed"）
                    Description = GetEnumMemberDescription(enumValue) // 枚举描述（从特性获取）
                }).OrderBy(item => (int)item.Value) // 按值升序排序
                .ToList();

            // 根据showDescription参数选择键（名称或描述），构建字典
            var dictionary = showDescription
                ? enumMembers.ToDictionary(m => m.Description, m => m.Value)
                : enumMembers.ToDictionary(m => m.Name, m => m.Value);

            // 转换为SortedDictionary（自动按键排序）
            return new SortedDictionary<string, object>(dictionary);
        }

        /// <summary>
        /// 辅助方法：获取枚举成员的Description特性值
        /// </summary>
        private static string GetEnumMemberDescription<TEnum>(TEnum enumValue)
            where TEnum : struct, Enum
        {
            // 获取枚举成员的反射信息
            MemberInfo[] memberInfo = typeof(TEnum).GetMember(enumValue.ToString());
            if (memberInfo.Length == 0)
                return enumValue.ToString(); // 无成员信息时返回名称

            // 尝试获取DescriptionAttribute特性
            var descriptionAttr = memberInfo[0].GetCustomAttribute<DescriptionAttribute>();
            return descriptionAttr?.Description ?? enumValue.ToString(); // 无特性时返回名称
        }


        /// <summary>
        /// 保存配置
        /// </summary>
        private static void SaveConfig(AutoAimConfig config)
        {
            try
            {
                string json = JsonUtility.ToJson(config, true); // 美化输出
                File.WriteAllText(FilePath, json);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }

        /// <summary>
        /// 加载配置，如果不存在则创建默认
        /// </summary>
        public static AutoAimConfig LoadConfig()
        {
            if (File.Exists(FilePath))
            {
                try
                {
                    string json = File.ReadAllText(FilePath);
                    if (json.Length <= 10)
                    {
                        throw new Exception("配置文件损坏, json:" + json);
                    }

                    AutoAimConfig config = JsonUtility.FromJson<AutoAimConfig>(json);
                    return config;
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                }
            }

            // 不存在或出错，创建默认并保存
            var defaultConfig = AutoAimConfig.Default;
            SaveConfig(defaultConfig);
            return defaultConfig;
        }

        /// <summary>
        /// 删除配置文件（重置）
        /// </summary>
        public static void ResetConfig()
        {
            if (File.Exists(FilePath))
            {
                File.Delete(FilePath);
            }
        }

        public static void OnBeforeDeactivate(AutoAimConfig config)
        {
            ModConfigAPI.SafeRemoveOnOptionsChangedDelegate(OnModConfigOptionsChanged);
            SaveConfig(config);
        }
    }
}